<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入规格名称"
          clearable
          maxlength="200"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:goodsspec:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:goodsspec:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:goodsspec:remove']"
        >删除</el-button>
      </el-col>
      <!--
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['shop:goodsspec:export']"
        >导出</el-button>
      </el-col>
      -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tables" v-loading="loading" :data="specList" @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规格编号" align="center" prop="id" />
      <el-table-column label="关联服务" align="center" prop="serviceNames">
        <template slot-scope="scope">
          <span>{{ newServiceNames(scope.row.serviceNames) || '通用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规格名称" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)" class="link-col">{{ scope.row.name }}</span>
          <!--<router-link :to="'/shop/specValue/index/' + scope.row.id" class="link-type">-->
            <!--<span>{{ scope.row.name }}</span>-->
          <!--</router-link>-->
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createDate" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:goodsspec:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:goodsspec:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" @submit.native.prevent :disabled="form.editType == 'detail'">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入规格名称" maxlength="40"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" class="inputClass" placeholder="" maxlength="300" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="相关服务">
          <div class="selected-items-panel">
            <div class="top">
                <span>通用规格</span>  <el-switch v-model="form.commonFlag" @change="changeCommonFlag"></el-switch>
                <el-button icon="el-icon-plus" class="add-btn" @click="addService" circle size="mini" :disabled="form.commonFlag" v-if="form.editType != 'detail'"></el-button>
            </div>
            <div class="content">
              <p class="tips" v-if="form.commonFlag">通用规格适用所有服务...</p>
              <template  v-for="(item, index) in form.serviceList" v-if="!form.commonFlag">
                <!--<el-tag size="mini" closable> {{ item.label }}</el-tag>-->
                <el-tag v-model="item.serviceCode" :closable="form.editType != 'detail'" @close="delService(item)" class="service-item">
                  {{ item.serviceName }}
                </el-tag>
              </template>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="规格属性值">
          <div class="tb-style1 spec-class-list">
            <el-row class="row header">
              <el-col class="li" :span="4">属性值序号</el-col>
              <el-col class="li" :span="10">开启状态</el-col>
              <el-col class="li" :span="10">属性值自定义名称</el-col>
            </el-row>
            <template v-for="(item, index) in form.specClassList">
              <el-row class="row">
                <el-col class="li" :span="4">{{index+1}}级属性</el-col>
                <el-col class="li" :span="10"><el-switch v-model="item.deleteFlag" @change="changeDeleteFlag(item)"></el-switch></el-col>
                <el-col class="li" :span="10"><el-input v-model.trim="item.name" placeholder="请输入自定义名称" maxlength="20" class="li-input" size="mini" /></el-col>
              </el-row>
            </template>
          </div>

          <template v-for="(item, index) in form.specClassList"  v-if="item.deleteFlag">
            <div class="tb-style1">
              <el-row class="row">
                <el-col class="li" :span="4">序号</el-col>
                <el-col class="li" :span="13"  :offset="4">{{ item.name }}</el-col>
                <el-col class="li" :span="3">
                  <el-button type="primary" icon="el-icon-plus" circle @click="addSpecValueItem(item)"></el-button>
                </el-col>
              </el-row>
              <template  v-for="(chil, idx) in item.specValueList" v-if="item.deleteFlag">
                <el-row class="row">
                  <el-col class="li" :span="4">{{idx+1}}</el-col>
                  <el-col class="li" :span="13" :offset="4"><el-input v-model.trim="chil.name" placeholder="请输入规格值名称" maxlength="20" class="li-input" size="mini" /></el-col>
                  <el-col class="li" :span="3">
                    <el-button type="primary" icon="el-icon-close" circle @click="deleteSpecValueItem(chil, item.specValueList)"></el-button>
                  </el-col>
                </el-row>
              </template>
            </div>

          </template>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="this.form.editType != 'detail'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" >取 消</el-button>
      </div>
    </el-dialog>


    <service-multiple-selector
      :dialogVisible.sync="showServiceSelector"
      @confirm="onServiceSelectorConfirm($event)"
    ></service-multiple-selector>
  </div>
</template>

<script>
  import { randomUUID } from "@/utils/index";
import { list, get, del, add, update } from "@/api/shop/spec/spec";
import ServiceMultipleSelector from "@/components/ServiceMultipleSelector";

export default {
  name: "Spec",
  components: {
    ServiceMultipleSelector
  },
  data() {
    return {
      //显示选择服务
      showServiceSelector: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      specList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 默认排序
      defaultSort: {prop: 'createDate', order: 'descending'},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        orderByColumn: 'createDate',
        isAsc: 'descending'
      },
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        remark: undefined,
        commonFlag: false,
        specClassList: [
          {deleteFlag:false, name:'', specValueList:[]},
          {deleteFlag:false, name:'', specValueList:[]},
          {deleteFlag:false, name:'', specValueList:[]},
        ],
        serviceList: [],
        editType:'detail'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "规格名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {

  },
  created() {
    this.getList();
  },
  methods: {
    newServiceNames(list){
      if(!list) return '';
      let txt = '';
      list.forEach((item, idx)=>{
        if(idx>0){
          txt += '、';
        }
        txt += item;
      });
      return txt
    },
    /** 查询规格列表 */
    getList() {
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.specList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        remark: undefined,
        commonFlag: false,
        specClassList: [
          {deleteFlag:false, name:'', specValueList:[]},
          {deleteFlag:false, name:'', specValueList:[]},
          {deleteFlag:false, name:'', specValueList:[]},
        ],
        serviceList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order);
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加规格";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.form.editType = 'edit';
      get(id).then(response => {
        let newData = {};
        newData['id'] = response.data.id || undefined;
        newData['editType'] = 'edit';
        newData['name'] = response.data.name;
        newData['remark'] = response.data.remark;
        newData['commonFlag'] = response.data.commonFlag;
        newData['serviceList'] = response.data.serviceList || [];
        newData['specClassList'] = [];

        for(let i=0;i<3;i++){
          if(response.data.specClassList[i]){
            let specClassItem = response.data.specClassList[i] || {deleteFlag:null,specValueList:[]};
            specClassItem.deleteFlag = (specClassItem['deleteFlag']==0)?true:false;
            // for(let j=0;j<3;j++){
            //   if(!specClassItem.specValueList[j]){
            //     specClassItem.specValueList[j] = {name:''};
            //   }
            // }
            newData['specClassList'].push(specClassItem);
          }else{
            newData['specClassList'].push({deleteFlag:false, name:'', specValueList:[]});
          }
        }
        this.form = JSON.parse(JSON.stringify(newData));
        console.log(this.form);
        this.open = true;
        this.title = "修改规格";
      });
    },
    /** 查看按钮操作 */
    handleDetail(row) {
      this.reset();
      const id = row.id || this.ids;
      this.form.editType = 'detail';
      get(id).then(response => {
        let newData = {};
        newData['id'] = response.data.id || undefined;
        newData['name'] = response.data.name;
        newData['editType'] =  'detail';
        newData['remark'] = response.data.remark;
        newData['commonFlag'] = response.data.commonFlag;
        newData['serviceList'] = response.data.serviceList || [];
        newData['specClassList'] = [];

        for(let i=0;i<3;i++){
          if(response.data.specClassList[i]){
            let specClassItem = response.data.specClassList[i] || {deleteFlag:null,specValueList:[]};
            specClassItem.deleteFlag = (specClassItem['deleteFlag']==0)?true:false;
            for(let j=0;j<3;j++){
              if(!specClassItem.specValueList[j]){
                specClassItem.specValueList[j] = {name:''};
              }
            }
            newData['specClassList'].push(specClassItem);
          }else{
            newData['specClassList'].push({deleteFlag:false, name:'', specValueList:[]});
          }
        }
        this.form = JSON.parse(JSON.stringify(newData));
        console.log(this.form);
        this.open = true;
        this.title = "查看规格";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      for (let i = 0; i < this.form.specClassList.length; i++) {
        let e = this.form.specClassList[i]
        if (e.deleteFlag&&e.name.trim().length==0) {
          this.$modal.msgError(`请输入${i+1}级属性的自定义名称`);
          return;
        }
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = {};
          params['name'] = this.form.name;
          params['remark'] = this.form.remark;
          params['commonFlag'] = this.form.commonFlag;
          params['serviceList'] = [];
          params['specClassList'] = [];

          if(!this.form.commonFlag){
            let serviceListLen = this.form.serviceList.length;
            for (let i=0;i<serviceListLen;i++){
              let itemInfo = this.form.serviceList[i];
              let newItem = {};
              newItem['serviceName'] = itemInfo.serviceName;
              newItem['serviceCode'] = itemInfo.serviceCode;
              if(itemInfo['id']){
                newItem['id'] = itemInfo.id;
              }
              params['serviceList'].push(newItem);
            }
          }

          for (let i=0;i<this.form.specClassList.length;i++){
            let itemInfo = this.form.specClassList[i];
            let newItem = {};
            if(itemInfo['id']){
              newItem['id'] = itemInfo.id;
            }
            newItem['name'] = itemInfo.name;
            newItem['deleteFlag'] = itemInfo.deleteFlag?0:1;
            if(itemInfo.specValueList && itemInfo.specValueList.length){
              newItem['specValueList'] = [];
              for(let j=0;j<itemInfo.specValueList.length;j++){
                if(itemInfo.specValueList[j] && itemInfo.specValueList[j]['name']){
                  let newSpecValueItem = {};
                  newSpecValueItem['name'] = itemInfo.specValueList[j].name;
                  if(itemInfo.specValueList[j]['id']){
                    newSpecValueItem['id'] = itemInfo.specValueList[j].id;
                  }
                  newItem['specValueList'].push(newSpecValueItem);
                }
              }
            }

            if(itemInfo.deleteFlag){
              params['specClassList'].push(newItem);
            }
          }
          console.log(params);
          if(!this.form.commonFlag && !params.serviceList.length){
            this.$modal.msgError("请添加服务");
            return
          }
          if(params.specClassList.length){
            if(!params.specClassList[0].specValueList.length){
              this.$modal.msgError("规格值名称不能为空");
              return
            }
          }else{
            this.$modal.msgError("规格属性不能为空");
            return
          }

          if (this.form.id != undefined) {
            params['id'] = this.form.id;
            update(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const specIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除规格编号为"' + specIds + '"的数据项？').then(function() {
        return del(specIds);
      }).then(() => {
        this.handleQuery();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shop/goodsspec/export', {
        ...this.queryParams
      }, `spec_${new Date().getTime()}.xlsx`)
    },
    changeCommonFlag(){
      console.log(this.form.commonFlag);
    },
    /**
     * 删除服务
     */
    delService(service){
      //删除服务
      let services = [];
      this.form.serviceList.forEach(element => {
        if (element.serviceCode != service.serviceCode) {
          services.push(element);
        }
      });
      this.form.serviceList = services;
    },
    /**
     * 添加服务
     */
    addService() {
      // if (this.editType === "detail") {
      //   return;
      // }
      this.showServiceSelector = true;
    },
    /**
     * 选中服务确认
     */
    onServiceSelectorConfirm(obj) {
      let { modelCodes, selectedItem } = obj
      //保存新增的服务
      let services = [];
      let serviceCodes = [];
      selectedItem.forEach(element => {
        services.push(element);
        serviceCodes.push(element.serviceCode);
      });
      //覆盖原页面的旧服务
      this.form.serviceList.forEach(element => {
        if (serviceCodes.indexOf(element.serviceCode) < 0) {
          services.push(element);
          serviceCodes.push(element.serviceCode);
        }
      });
      console.log(services);
      this.form.serviceList = services;
      // this.goods.services = services;
    },
    changeDeleteFlag(item){
      console.log(item);
      if(!item.name){
        this.$modal.msgError("请输入自定义名称");
        item.deleteFlag = false;
      }
      if(item.deleteFlag && !item.specValueList.length){
        item.specValueList = [
          {name:'',uuid:randomUUID()}
        ];
      }
    },
    addSpecValueItem(specClassItem){
      // console.log(specClassItem);
      if(!this.form.commonFlag && specClassItem.specValueList.length >= 5){
        this.$modal.msgError("非通用规格不能超过5个属性值");
        return
      }
      specClassItem.specValueList.push({name:'',uuid:randomUUID()});
    },
    deleteSpecValueItem(specValueItem, specValueList){
      // console.log(specValueItem);
      for(let i=0;i<specValueList.length;i++){
        let itemInfo = specValueList[i];
        if(specValueItem.hasOwnProperty('id')){
          if(specValueItem.id === itemInfo.id){
            specValueList.splice(i,1);
            return
          }
        }else{
          if(specValueItem.uuid === itemInfo.uuid){
            specValueList.splice(i,1);
            return
          }
        }
      }
    }
  }
};
</script>
<style scoped>
/* element-ui input style overload */
::v-deep .inputClass > textarea {
  padding-right: 55px;
}

.selected-items-panel{
  border: 1px solid #ddd;
  border-radius: 6px;
  min-height: 100px;
  overflow: hidden;
}

.selected-items-panel .top{
  background-color: #ccc;
  height: 40px;
  padding: 0 10px;
}

.selected-items-panel .top .add-btn{
  float: right;
  margin-top: 6px;
}

.selected-items-panel .content{
  padding: 10px;
}
.selected-items-panel .content .tips{
  text-align: center;
}

.selected-items-panel .content  .service-item{
  margin: 5px;
}

.tb-style1{
  border: 1px solid #ccc;
  margin-bottom: 20px;
}
.tb-style1 .row{
  list-style-type:none;
  padding: 0;
  border-bottom: 1px solid #ccc;
}
.tb-style1 .row:last-child{
  border-bottom: none;
}
.tb-style1 .row .li{
  float: left;
  text-align: center;
  padding: 5px;
}

.link-col{
  color: #1890ff;
  cursor: pointer;
}
</style>
